import { rollup, defineConfig } from "rollup";
import path from "path";

import dts from "rollup-plugin-dts";

import ProgressBar from "progress";
const entryDir = path.resolve("./src/");
const outputDir = path.resolve("./lib/");
import postcss from "rollup-plugin-postcss";
import esbuild from "rollup-plugin-esbuild";

const baseConfig = defineConfig({
  external: [
    "react",
    "react-dom",
    "styled-components",
    "react/jsx-runtime",
    "react-countup",
    "lodash",
    "lodash-es",
    "echarts-for-react",
    "react-dom/client",
    "echarts",
    "react-scroll",
    "nanoid",
    "react-resize-detector",
    "react-responsive",
    "scroll-into-view-if-needed",
    "@core/shared",
    "cronstrue",
    "cronstrue/locales/zh_CN",
    "classnames",
    "antd",
    "dayjs",
    "rc-util/lib/hooks/useMergedState",
    "rc-util",
  ],
  input: path.resolve(entryDir, "./index.ts"),
  output: {
    dir: outputDir,
  },
  plugins: [
    esbuild(),
    postcss({
      extensions: [".css", ".less"],
      // modules: true,
      extract: true,
      plugins: [],
    }),
  ],
});

async function buildAll(bar) {
  const bundle = await rollup(
    defineConfig({
      ...baseConfig,
      treeshake: true,
      input: path.resolve(entryDir, "./index.ts"),
    })
  );
  bar.tick();
  bar.interrupt("bundle已生成,开始写入文件");
  await bundle.write({
    dir: outputDir,
    format: "es",
    preserveModules: true,
  });

  bar.tick();
  await bundle.close();
  bar.tick();
  bar.interrupt("开始构建类型文件");
  const dtsBundle = await rollup(
    defineConfig({
      ...baseConfig,
      external: [/\.scss$/, /\.less$/, /\.css$/],
      plugins: [dts()],
    })
  );
  bar.tick();
  await dtsBundle.write({
    dir: outputDir,
    format: "es",
    preserveModules: true,
  });
  bar.tick();
  await dtsBundle.close();
  bar.tick();
  bar.interrupt("全部构建完成");
}

async function buildLib() {
  const bar = new ProgressBar(
    "黄师傅正在构建中 [:bar]  :percent :current/:total",
    {
      complete: "=",
      incomplete: " ",
      width: 20,
      total: 6,
    }
  );

  bar.interrupt("程序启动");

  await buildAll(bar);
}

buildLib();
